package cn.nfwx.tv.controller.me;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;

import org.greenrobot.eventbus.EventBus;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.nfwx.tv.R;
import cn.nfwx.tv.adapter.AppiontmentAdapter;
import cn.nfwx.tv.base.BaseFragment;
import cn.nfwx.tv.callback.ResponseListener;
import cn.nfwx.tv.controller.DownloadM3u8Controller;
import cn.nfwx.tv.controller.TVProgramsViewController;
import cn.nfwx.tv.db.DownProgramModel;
import cn.nfwx.tv.db.TvAppointment;
import cn.nfwx.tv.events.PlayEvents;
import cn.nfwx.tv.fragment.me.MineAllFragment;
import cn.nfwx.tv.fragment.me.MineFragment;
import cn.nfwx.tv.helper.AccountHelper;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.helper.NetworkHelper;
import cn.nfwx.tv.helper.ThreadHelper;
import cn.nfwx.tv.helper.ValueCallback;
import cn.nfwx.tv.manager.AppointmentManager;
import cn.nfwx.tv.model.Result;
import cn.nfwx.tv.model.TvProgram;
import cn.nfwx.tv.util.SharePrefUtil;
import cn.nfwx.tv.util.TimeUtil;
import cn.nfwx.tv.util.ToastUtil;
import cn.nfwx.tv.vo.AppiontmentSection;
import cn.nfwx.tv.widget.LoadView;

/**
 * Created by zhouzechao on 2018/5/23.
 */

public class MineAppointmentController implements AppiontmentAdapter.OnCheckedChangeDelListener {
    private Context mContext;
    private MineAllFragment mFragment;
    private RecyclerView mRecyclerView;
    private LoadView mLoadView;
    private TwinklingRefreshLayout trl_mine;
    private View notDataView;
    private TextView edit_mine_btn;
    private TextView tv_mine_select;

    private AppiontmentAdapter appiontmentAdapter;
    private List<AppiontmentSection> tvPrograms = new ArrayList<>();
    private String requestTvAppointCommand, requestTvAppointDelCommand;


    public MineAppointmentController(Context context, MineAllFragment fragment) {
        mContext = context;
        mFragment = fragment;
    }

    public void init(RecyclerView recyclerView, LoadView loadView, final TwinklingRefreshLayout trl_mine, View notDataView, TextView edit_mine_btn) {
        mRecyclerView = recyclerView;
        mLoadView = loadView;
        this.trl_mine = trl_mine;
        this.notDataView = notDataView;
        this.edit_mine_btn = edit_mine_btn;

        if (appiontmentAdapter == null) {
            appiontmentAdapter = new AppiontmentAdapter();
        }
        mRecyclerView.setAdapter(appiontmentAdapter);

        appiontmentAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Object o = adapter.getData().get(position);
                if (o instanceof AppiontmentSection) {
                    AppiontmentSection appiontmentSection = (AppiontmentSection) o;
                    if (appiontmentSection.t instanceof TvAppointment) {
                        TvAppointment tvAppointment = (TvAppointment) appiontmentSection.t;
                        if (appiontmentAdapter.isDelete()) {
                            tvAppointment.setCheck(!tvAppointment.isCheck());
                            adapter.notifyItemChanged(position);
                        } else {
                            if (!TextUtils.isEmpty(tvAppointment.getUrl())) {
                                PlayEvents events = new PlayEvents(tvAppointment.getProgram_id(), tvAppointment.getUrl(), null, tvAppointment.getProgram_name(), 0);
                                if (mFragment.getParentFragment() instanceof MineFragment) {
                                    MineFragment mineFragment = (MineFragment) mFragment.getParentFragment();
                                    mineFragment.isBackEvent = false;
                                    events.setFragment(PlayEvents.MINE);
                                    events.setMePosition(MineFragment.POSITION_APPOINT);
                                    events.setTag("mineFragment");
                                }
                                EventBus.getDefault().post(events);
                            } else {
                                if (tvAppointment.isLive()) {
                                    if (mFragment.getParentFragment() instanceof MineFragment) {
                                        MineFragment mineFragment = (MineFragment) mFragment.getParentFragment();
                                        SharePrefUtil.saveIjkLiveId(mContext, tvAppointment.getChannel());
                                        mineFragment.dismissAllowingStateLoss();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        });

        appiontmentAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, final int position) {
                Object o = adapter.getData().get(position);
                if (o instanceof AppiontmentSection) {
                    AppiontmentSection appiontmentSection = (AppiontmentSection) o;
                    if (appiontmentSection.t instanceof TvAppointment) {
                        TvAppointment tvAppointment = (TvAppointment) appiontmentSection.t;
                        if (!AccountHelper.getInstance().isLogin(mContext)) {
                            ToastUtil.show(mContext, "用户未登录", Toast.LENGTH_LONG);
                            return;
                        }
                        if (!TextUtils.isEmpty(tvAppointment.getUrl())) {
                            // 回看更新下载ui
                            if (!NetworkHelper.getInstance().hasConnection(mContext)) {
                                ToastUtil.show(mContext, R.string.nointernet, Toast.LENGTH_LONG);
                                return;
                            }
                            if (NetworkHelper.getInstance().isConnection4g(mContext)
                                    && !SharePrefUtil.getDownloadChoose(mContext)) {
                                ToastUtil.show(mContext, R.string.download_4g);
                                return;
                            }
                            TvProgram tvProgram = new TvProgram();
                            tvProgram.setProgram_name(tvAppointment.getProgram_name());
                            tvProgram.setTime(tvAppointment.getProgram_time());
                            tvProgram.setUrl(tvAppointment.getUrl());
                            tvProgram.setGid(tvAppointment.getChannel());
                            tvProgram.setProgram_id(tvAppointment.getProgram_id());
                            tvProgram.setType(0);
                            DownloadM3u8Controller.getInstance().download(mContext, tvProgram, mFragment.<Integer>bindToLifecycle(), new ValueCallback<Integer>() {
                                @Override
                                public void onReceiveValue(Integer value) {
                                    if (value == DownProgramModel.STATS_FAIL) {
                                        ToastUtil.show(mContext, "下载失败");
                                    } else if (value == DownProgramModel.STATS_DOWNLOADED) {
                                        ToastUtil.show(mContext, "已正在下载");
                                    } else {
                                        appiontmentAdapter.notifyItemChanged(position);
                                        ToastUtil.show(mContext, "正在下载");
                                    }
                                }
                            });
                        }
                    }
                }
            }
        });

        appiontmentAdapter.setOnCheckedChangeDelListener(this);
    }

    public void bindTvAppointData() {
        appiontmentAdapter.setEmptyView(new View(mContext));
        appiontmentAdapter.setNewData(new ArrayList<AppiontmentSection>());
        if (tvPrograms.isEmpty()) {
            //mLoadView.startLoading(trl_mine);
            requestTvAppointCommand = AppointmentManager.requestAppointmentList(mContext, responseListener);
        } else {
            appiontmentAdapter.setNewData(tvPrograms);
            trl_mine.finishRefreshing();
        }
    }

    public void changeDelete() {
        appiontmentAdapter.setDelete(!isDelete());
    }

    public boolean isDelete() {
        return appiontmentAdapter.isDelete();
    }

    public boolean isSelectAll() {
        return appiontmentAdapter.isSelectAll();
    }

    public void changeSelectAll() {
        appiontmentAdapter.setSelectAll(!isSelectAll());
    }

    public void deleteSelect() {
        List<TvAppointment> tvAppointments = appiontmentAdapter.getDeleteDatas();
        Map<String, List<Integer>> map = new HashMap<>();
        for (TvAppointment tvAppointment : tvAppointments) {
            String gid = tvAppointment.getChannel();
            if (map.containsKey(gid)) {
                List<Integer> program_ids = map.get(gid);
                program_ids.add(tvAppointment.getProgram_id());
            } else {
                List<Integer> program_ids = new ArrayList<>();
                program_ids.add(tvAppointment.getProgram_id());
                map.put(gid, program_ids);
            }
        }
        if (map.isEmpty()) {
            ToastUtil.show(mContext, "选择要删除的节目");
            return;
        }
        DialogFragmentHelper.showLoadingDialog(mFragment.getChildFragmentManager());
        for (Map.Entry<String, List<Integer>> e : map.entrySet()) {
            requestTvAppointDelCommand = AppointmentManager.requestDelAppointment(mContext, e.getKey(), responseListener, e.getValue());
        }
    }

    ResponseListener responseListener = new ResponseListener<String>() {
        @Override
        public void onResponse(final String requestTag, final String response) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (requestTag.equals(requestTvAppointCommand)) {
                        trl_mine.finishRefreshing();
                        mLoadView.removeParentView(trl_mine);
                        Result<List<TvAppointment>> result = JSON.parseObject(response, new TypeReference<Result<List<TvAppointment>>>() {
                        }.getType());
                        if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
                            if (result.getData().isEmpty()) {
                                edit_mine_btn.setVisibility(View.GONE);
                                mFragment.hideBottom();
                                appiontmentAdapter.setEmptyView(notDataView);
                                appiontmentAdapter.setNewData(new ArrayList<AppiontmentSection>());
                            } else {
                                List<TvAppointment> list = result.getData();
                                Collections.sort(list, new Comparator<TvAppointment>() {
                                    @Override
                                    public int compare(TvAppointment o1, TvAppointment o2) {
                                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                        try {
                                            Date dt1 = format.parse(o1.getProgram_time());
                                            Date dt2 = format.parse(o2.getProgram_time());
                                            if (dt1.getTime() > dt2.getTime()) {
                                                return 1;
                                            } else if (dt1.getTime() < dt2.getTime()) {
                                                return -1;
                                            } else {
                                                return 0;
                                            }
                                        } catch (Exception e) {
                                            e.printStackTrace();
                                        }
                                        return 0;
                                    }
                                });
                                List<String> dates = new ArrayList<>();
                                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                                List<AppiontmentSection> appiontmentSections = new ArrayList<>();
                                for (TvAppointment tvAppointment : list) {
                                    tvAppointment.setCheck(false);
                                    try {
                                        Date date = dateFormat.parse(tvAppointment.getProgram_time());
                                        String yyyyMMdd = TimeUtil.getFormatYYMMddTime(date);
                                        if (dates.contains(yyyyMMdd)) {
                                            appiontmentSections.add(new AppiontmentSection(tvAppointment));
                                        } else {
                                            appiontmentSections.add(new AppiontmentSection(true, TimeUtil.getFormatMMddDate(date)));
                                            appiontmentSections.add(new AppiontmentSection(tvAppointment));
                                            dates.add(yyyyMMdd);
                                        }
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                }
                                if (appiontmentSections.isEmpty()) {
                                    edit_mine_btn.setVisibility(View.GONE);
                                    appiontmentAdapter.setEmptyView(notDataView);
                                    appiontmentAdapter.setNewData(appiontmentSections);
                                } else {
                                    edit_mine_btn.setVisibility(View.VISIBLE);
                                    tvPrograms.clear();
                                    tvPrograms.addAll(appiontmentSections);
                                    appiontmentAdapter.setNewData(appiontmentSections);
                                }
                            }
                        }
                    } else if (requestTag.equals(requestTvAppointDelCommand)) {
                        DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
                        Result result = JSON.parseObject(response, new TypeReference<Result>() {
                        }.getType());
                        if (result.getMessage().equals(Result.RESULT_SUCCESS)) {
                            tvPrograms.clear();
                            requestTvAppointCommand = AppointmentManager.requestAppointmentList(mContext, responseListener);
                        }
                    }
                }
            });
        }

        @Override
        public void onError(final String requestTag, final Throwable t) {
            ThreadHelper.post(new Runnable() {
                @Override
                public void run() {
                    if (requestTag.equals(requestTvAppointCommand)) {
                        mLoadView.loadError(trl_mine);
                        trl_mine.finishRefreshing();
                    } else if (requestTag.equals(requestTvAppointDelCommand)) {
                        DialogFragmentHelper.closeLoadingDialog(mFragment.getChildFragmentManager());
                        ToastUtil.show(mContext, "删除失败");
                    }
                }
            });
        }

        @Override
        public void onFinish() {

        }
    };

    @Override
    public void onCheckedAllChanged(boolean stats) {
        if (stats) {
            tv_mine_select.setText("取消全选");
        } else {
            tv_mine_select.setText("全选");
        }
    }

    public void setDeteleView(TextView deteleView) {
        this.tv_mine_select = deteleView;
    }
}
